package cn.lastcc.pwdmanage.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Date;
import java.util.List;

import cn.lastcc.pwdmanage.R;
import cn.lastcc.pwdmanage.core.AesUtil;
import cn.lastcc.pwdmanage.core.CustomApp;
import cn.lastcc.pwdmanage.core.MD5;
import cn.lastcc.pwdmanage.core.SerialUtil;
import cn.lastcc.pwdmanage.entity.IConstant;
import cn.lastcc.pwdmanage.entity.Info;
import cn.lastcc.pwdmanage.entity.PwdTag;

public class UserPwdModifyActivity extends Activity {

    private SerialUtil mSerialUtil = null;

    // 声明控件
    private EditText txtOriginPwd = null;
    private EditText txtPwd = null;
    private EditText txtConfirmPwd = null;
    private Button btnSavePwd = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("修改用户密码");
        mSerialUtil = SerialUtil.getInstance(this);
        setContentView(R.layout.activity_user_pwd_modify);
        // Show the Up button in the action bar.
//        setupActionBar();
        // 根据 ID 获得控件对象
        this.txtOriginPwd = (EditText) this.findViewById(R.id.txtOriginPwd_upm);
        this.txtPwd = (EditText) this.findViewById(R.id.txtPwd_upm);
        this.txtConfirmPwd = (EditText) this.findViewById(R.id.txtConfirmPwd_upm);
        this.btnSavePwd = (Button) this.findViewById(R.id.btnSavePwd_upm);
        Info info = null;
        try {
            info = mSerialUtil.getInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 第一次使用不要求输入旧密码，所以把旧密码文本框置灰
        if (null == info) {
            this.txtOriginPwd.setEnabled(false);
            this.txtPwd.requestFocus();
        }
        this.btnSavePwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	CustomApp customApp = (CustomApp) UserPwdModifyActivity.this.getApplication();
            	MD5 m = new MD5();
                Info info = null;
                String originPwdText = "";

                try {
                    info = mSerialUtil.getInfo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 第一次使用不要求输入旧密码
                if (null != info) {
                    originPwdText = txtOriginPwd.getText().toString();
                    if ("".equals(originPwdText)) {
                        Toast.makeText(v.getContext(), R.string.msg_userPwdModifyActivity_originPwdEmpty, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String originPwd = m.cell32(originPwdText);
                    if (!originPwd.equals(info.getUserPassword())) {
                        Toast.makeText(v.getContext(), R.string.msg_userPwdModifyActivity_originPwdFailed, Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    info = new Info();
                }
                final String pwdText = txtPwd.getText().toString();
                final String confirmPwdText = txtConfirmPwd.getText().toString();
                if ("".equals(pwdText)) {
                    Toast.makeText(v.getContext(), R.string.msg_userPwdModifyActivity_pwdEmpty, Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(confirmPwdText)) {
                    Toast.makeText(v.getContext(), R.string.msg_userPwdModifyActivity_confirmPwdEmpty, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!pwdText.equals(confirmPwdText)) {
                    Toast.makeText(v.getContext(), R.string.msg_userPwdModifyActivity_pwdNotConfirm, Toast.LENGTH_SHORT).show();
                    return;
                }
                info.setUserPassword(m.cell32(pwdText));
                List<PwdTag> pwdTagList=info.getPwdTagList();
                for (int i = 0, j = pwdTagList.size(); i < j; i++) { // 第一次使用不会进入循环
                    PwdTag pwdTag = pwdTagList.get(i);
                    pwdTag.setModifyDate(new Date());
                    pwdTag.setModifyTimes(pwdTag.getModifyTimes() + 1);
                    byte[] originSalt = pwdTag.getSalt();
                    // 更新盐值
                    byte[] newSalt = new byte[IConstant.LENGTH_SALT];
                    AesUtil.generateSalt(newSalt);
                    pwdTag.setSalt(newSalt);
                    // 更新TAG
                    byte[] nameResult = AesUtil.decrypt(AesUtil.parseHexStr2Byte(pwdTag.getTagName()), originPwdText, originSalt);
                    String _nameStr = new String(nameResult);
                    pwdTag.setTagName(AesUtil.parseByte2HexStr(AesUtil.encrypt(_nameStr, pwdText, newSalt)));
                    // 更新密码
                    byte[] pwdResult = AesUtil.decrypt(AesUtil.parseHexStr2Byte(pwdTag.getPwd()), originPwdText, originSalt);
                    String _pwdStr = new String(pwdResult);
                    pwdTag.setPwd(AesUtil.parseByte2HexStr(AesUtil.encrypt(_pwdStr, pwdText, newSalt)));
                }
                info.setPwdTagList(pwdTagList);
                customApp.setUserPwd(pwdText);
                info.setVersionCode(customApp.getVersionCode());
                info.setVersionName(customApp.getVersionName());
                info.setFileVersion(IConstant.INFO_CUR_VERSION_STR);
                try {
                    mSerialUtil.setInfo(info);
                    Intent intent = new Intent();
                    intent.setClass(UserPwdModifyActivity.this, LogonActivity.class);
                    startActivity(intent);
                    MainActivity.instance.finish();
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(v.getContext(), R.string.msg_userPwdModifyActivity_savePwdFailed, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
}
